﻿using System;
using System.Net.Http;
using Wireframe;

namespace SampleWebCrawler
{
    /// <summary>
    ///     Represents an event handler for html loading events.
    /// </summary>
    public sealed class HtmlLoader
    {
        private readonly HttpClient _httpClient;

        public HtmlLoader()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        ///     Handles load html event.
        /// </summary>
        /// <param name="message">Event data with URI.</param>
        public async void HandleLoadHtmlEvent(LoadHtmlEvent message)
        {
            // This method will be called when "LoadHtmlEvent" is sent.

            string content = null;

            try
            {
                using (HttpResponseMessage response = await _httpClient.GetAsync(message.Value))
                {
                    content = await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception e)
            {
                // If message is raised "LogExceptionEvent" will be sent.
                this.Send(new LogExceptionEvent(e));
            }

            if (!string.IsNullOrEmpty(content))
            {
                // In case of not null content "ParseHtmlEvent" is sent.
                this.Send(new ParseHtmlEvent(content));
            }
        }
    }
}